//
//  IMAdStrategyService.m
//  DualMediationSDK
//
//  广告策略服务实现
//  Created by YeJary on 2025/7/15.
//

#import "IMAdStrategyService.h"
#import "IMAdStrategyModels.h"
#import "../HTTP/YKHTTPService.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "IMAdStrategyManager.h"
#import "../TA/DMThinkingManager.h"

@implementation IMAdStrategyService

#pragma mark - 单例

+ (instancetype)sharedService {
    static IMAdStrategyService *_sharedService = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedService = [[IMAdStrategyService alloc] init];
    });
    return _sharedService;
}

#pragma mark - 公共方法

- (void)getAdStrategyWithAppId:(NSString *)appId
                          uuid:(NSString *)uuid
                       success:(void(^)(IMAdStrategyResponse *response))success
                       failure:(void(^)(NSError *error))failure {
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"IMAdStrategyService" 
                                             code:-1001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"appId不能为空"}];
        if (failure) {
            failure(error);
        }
        return;
    }
    
    if (!uuid || uuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"IMAdStrategyService" 
                                             code:-1002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"uuid不能为空"}];
        if (failure) {
            failure(error);
        }
        return;
    }
    
    // 创建请求模型
    IMAdStrategyRequest *request = [IMAdStrategyRequest requestWithAppId:appId uuid:uuid];
    
    // 调用请求方法
    [self getAdStrategyWithRequest:request success:success failure:failure];
}

- (void)getAdStrategyWithRequest:(IMAdStrategyRequest *)request
                         success:(void(^)(IMAdStrategyResponse *response))success
                         failure:(void(^)(NSError *error))failure {
    
    // 参数验证
    if (!request) {
        NSError *error = [NSError errorWithDomain:@"IMAdStrategyService" 
                                             code:-1003 
                                         userInfo:@{NSLocalizedDescriptionKey: @"请求参数不能为空"}];
        if (failure) {
            failure(error);
        }
        return;
    }
    
    // 记录请求日志
    [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 开始请求广告策略"];
    [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 请求参数: %@", request];
    
    // 构建请求参数
    NSDictionary *parameters = [request toDictionary];
    
    // 发起网络请求
    [YKHTTPService POST:@"/api/wsdk/adStrategy"
             parameters:parameters
                success:^(IMNetworkResponse *networkResponse) {
                    [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 广告策略请求成功"];
                    [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 响应数据: %@", networkResponse.data];
                    
                    // 解析响应数据
                    IMAdStrategyResponse *response = [IMAdStrategyResponse responseFromDictionary:networkResponse.data];
                    
                    if (response) {
                        if (response.isSuccess) {
                            [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 广告策略获取成功，场景数量: %lu", (unsigned long)response.data.count];
                            // 使用IMAdStrategyManager单例来更新和存储策略数据
                            [[IMAdStrategyManager sharedManager] updateStrategiesFromResponse:response];
                            
                            if (success) {
                                success(response);
                            }
                        } else {
                            NSString *errorMessage = [NSString stringWithFormat:@"服务器返回错误: %@ (code: %ld)", response.message, (long)response.code];
                            [IMLogUtils error:IMLogTagNetwork format:@"[AdStrategy] %@", errorMessage];
                            
                            NSError *error = [NSError errorWithDomain:@"IMAdStrategyService" 
                                                                 code:response.code 
                                                             userInfo:@{NSLocalizedDescriptionKey: errorMessage}];
                            if (failure) {
                                failure(error);
                            }
                        }
                    } else {
                        NSString *errorMessage = @"响应数据解析失败";
                        [IMLogUtils error:IMLogTagNetwork format:@"[AdStrategy] %@", errorMessage];
                        
                        NSError *error = [NSError errorWithDomain:@"IMAdStrategyService" 
                                                             code:-1004 
                                                         userInfo:@{NSLocalizedDescriptionKey: errorMessage}];
                        if (failure) {
                            failure(error);
                        }
                    }
                }
                failure:^(IMNetworkResponse *response) {
                    [IMLogUtils error:IMLogTagNetwork format:@"[AdStrategy] 广告策略请求失败: %@", response.error.localizedDescription];
                    
                    // 记录降级事件到ThinkingData
                    NSDictionary *eventProps = @{
                        @"w_interface_path": @"/api/wsdk/adStrategy",
                        @"w_http_code": @(response.statusCode),
                        @"w_http_msg": response.error.localizedDescription ?: @"",
                        @"w_action": @"apply_default_sdk_config"
                    };
                    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_STRATEGY_FALLBACK" properties:eventProps];
                    
                    // 应用默认SDK启动配置以保障稳定性
                    [IMLogUtils info:IMLogTagNetwork format:@"[AdStrategy] 应用默认SDK启动配置以降级保障"];
                    [[IMAdStrategyManager sharedManager] applySDKStartupConfiguration];
                    
                    if (failure) {
                        failure(response.error);
                    }
                }];
}

@end
